package org.wpahs.ahn.rssfeed.DB;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import org.wpahs.ahn.rssfeed.R;

/**
 * Base class for all DB tables.  Handles creation and update
 * Created by dgambone on 01/15/2015.
 */
public class FeedsDB extends SQLiteOpenHelper {
    public FeedsDB(Context context) {
        super(context,
                context.getString(R.string.DB_Settings),
                null,
                context.getResources().getInteger(R.integer.DB_Version)
        );
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        CreateTable(db,DBMyFeed.DB.TABLE_NAME,DBMyFeed.DB.SQL_CREATE_TABLE);
        CreateTable(db,DBFeedItem.DB.TABLE_NAME,DBFeedItem.DB.SQL_CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //DropTable(DBFeedItem.DB.TABLE_NAME);

        try {
            if (newVersion > oldVersion) {
                //db.execSQL("ALTER TABLE " + DBFeedItem.DB.TABLE_NAME + " ADD COLUMN " + DBFeedItem.DB.COLUMN_FAVORITE + " INTEGER DEFAULT 0");
                db.execSQL("ALTER TABLE " + DBMyFeed.DB.TABLE_NAME + " ADD COLUMN " + DBMyFeed.DB.COLUMN_IMAGE + " TEXT_TYPE DEFAULT null");

            }
        }catch (Exception ex){
            Log.e("FeedsDB-onUpgrade", ex.getMessage());
        }

    }

    public void DropTable(String table){
        getWritableDatabase().execSQL("DROP TABLE " + table);
    }

    private void CreateTable(SQLiteDatabase db,String table,String createStr){
        Cursor cursor = db.rawQuery(
                "select DISTINCT tbl_name from sqlite_master where tbl_name = '" + table + "'",
                null
        );
        if(cursor!=null) {
            if (cursor.getCount() > 0) {
                cursor.close();
            }else{
                db.execSQL(createStr);
            }
            cursor.close();
        }else{
            db.execSQL(createStr);
        }
    }


}
